package com.example.server.security;

import com.example.server.exception.YebException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 注册到IOC容器
 * @author CuiQingFeng
 */
@Component
public class DefaultSessionBasedAuthenticateInterceptor implements HandlerInterceptor {

    @Value("${yeb.enable-authenticated-annotation}")
    private boolean enableAuthenticated;

    /**
     * 在执行正常的controller功能之前会执行的代码
     * 在该代码中可以执行筛选，只有登录用户可以访问受保护资源
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            Authenticated authenticated = handlerMethod.getMethodAnnotation(Authenticated.class);

            if (!enableAuthenticated || ( enableAuthenticated && authenticated != null)){
                //获取session对象
                HttpSession session = request.getSession();
                //验证session是否已经登录过了
                Object auth = session.getAttribute("auth");
                //没有登录抛出异常
                if (auth == null){
                    throw new YebException(401, "用户未登录/登录过期，请登录");
                }

                return true;
            }
        }
        return true;

    }
}
